terraform {
  required_providers {
    yandex = {
      source  = "yandex-cloud/yandex"
      version = ">= 0.13"
    }
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.5"
    }
    local = {
      source  = "hashicorp/local"
      version = "2.2.2"
    }
  }
}

provider "yandex" {
  service_account_key_file = var.path_to_sa
  cloud_id                 = var.cld_id
  folder_id                = var.fldr_id
  zone                     = var.zn
}

provider "aws" {
  region     = var.aws_region
  access_key = var.my_aws_access_key
  secret_key = var.my_aws_secret_key
}

/* AUXILIARY BLOCK */

# recieve yandex subnet name
data "yandex_vpc_subnet" "admin" {
  name = var.subnet_name
}

# create a metadata.yml
resource "local_file" "metadata_yml" {
  content = templatefile("${path.module}/metadata.tpl",
    {
      mykeys = var.list_my_keys
      user   = var.my_user
    }
  )
  filename = "${path.module}/metadata.yml"
}


# Create a new instance
resource "yandex_compute_instance" "vm-proxy" {
  name = var.proxy_name

  resources {
    cores         = var.cores_count
    core_fraction = var.core_fract
    memory        = var.ram_size
  }

  boot_disk {
    initialize_params {
      image_id = var.bdisk
    }
  }

  network_interface {
    subnet_id = data.yandex_vpc_subnet.admin.id
    nat       = true
  }

  metadata = {
    user-data = local_file.metadata_yml.content
  }

  labels = {
    user_email = var.tag_my_mail,
    task_name  = var.tag_learn_module
  }

}


/* General jobs of the AWS Route */

# recieve hosted zone
data "aws_route53_zone" "selected" {
  name         = var.my_hosted_zone_on_aws
  private_zone = false
}

# Creating a dns entry for yandex instance in the AWS
resource "aws_route53_record" "proxy" {
  zone_id    = data.aws_route53_zone.selected.zone_id
  name       = split("@", var.tag_my_mail)[0]
  type       = "A"
  ttl        = "300"
  records    = [yandex_compute_instance.vm-proxy.network_interface.0.nat_ip_address]
  depends_on = [yandex_compute_instance.vm-proxy]
}


/* GENERATE CONTENT BLOCK */

# create a json of output data
resource "local_file" "result_data" {
  content = templatefile("${path.module}/inventory.tpl",
    {
      proxy_name = yandex_compute_instance.vm-proxy.name
      proxy_ip   = yandex_compute_instance.vm-proxy.network_interface.0.nat_ip_address
      site_name  = aws_route53_record.proxy.fqdn
      user       = var.my_user
    }
  )
  filename = "${path.module}/inventory"
}
